import { DotLoading, Mask, Toast } from "antd-mobile";
import React, { Suspense, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Route,
  Routes,
  useLocation,
  useNavigate,
  useParams,
  useSearchParams,
} from "react-router-dom";
import { setUserInfoAsync } from "../store/slice/baseSlice";
import routes from "./routes";

// 统一路由配置
const Element = function Element(props) {
  let { component: Component, meta, path } = props.item;
  const { userInfo } = useSelector((state) => state.base);
  const checkList = ["/personal", "/store", "/update"];
  const dispatch = useDispatch();
  // 函数组件更新，state改变就更新。
  let [_, setRandom] = useState(0);
  useEffect(() => {
    // 登录态校验
    // redux中没有存userInfo 以及跳转的路径是需要登录的
    if (!userInfo && checkList.includes(path)) {
      //没有token值就跳到登录页。
      if (!localStorage.tk) {
        Toast.show({
          icon: "fail",
          content: "请先登录",
        });
        // 跳转到登录页
        navigate(
          {
            pathname: "/login",
            search: `?to=${path}`,
          },
          { replace: true }
        );
      }
      // 有token值就派发一下，存储userInfo
      dispatch(setUserInfoAsync());
      setRandom(+new Date());
    }
  });
  // 修改页面的title
  let { title = "知乎日报-WebApp" } = meta || {};
  document.title = title;

  // 获取路由信息，基于属性传递给组件
  const navigate = useNavigate(),
    location = useLocation(),
    params = useParams(),
    [usp] = useSearchParams();

  return (
    <Component
      navigate={navigate}
      location={location}
      params={params}
      usp={usp}
    ></Component>
  );
};
export default function RouterView() {
  return (
    <Suspense
      fallback={
        <Mask visible={true}>
          <DotLoading color='white' />
        </Mask>
      }
    >
      <Routes>
        {routes.map((item) => {
          let { name, path } = item;
          return (
            <Route
              key={name}
              path={path}
              element={<Element item={item} />}
            ></Route>
          );
        })}
      </Routes>
    </Suspense>
  );
}
